package com.mall.utils;

import com.mall.pojo.Result;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.server.ResponseStatusException;

public class JwtUtils {
    private static final String SECRET_KEY = "SECRET_KEY_SET_IN_2025_4_20_BY_WHU";

    public static void validateToken(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("Token格式");
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "请先登录");
        }

        token = token.substring(7);
        try {
            Jwts.parser()
                    .verifyWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()))
                    .build()
                    .parseSignedClaims(token);
        } catch (ExpiredJwtException e) {
            System.out.println("过期");
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Token已过期,请重新登录");
        } catch (Exception e) {
            System.out.println("无效");
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Token无效");
        }
    }

}